<template>
  <div class="todo-container">
    <h2>Todo List</h2>
    <el-input
      v-model="newTodo"
      placeholder="请输入待办事项"
      @keyup.enter="addTodo"
      style="width: 300px; margin-bottom: 20px"
    >
      <template #append>
        <el-button @click="addTodo" :icon="Plus" />
      </template>
    </el-input>

    <el-table :data="todos" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="content" label="内容" />
      <el-table-column label="状态" width="120">
        <template #default="{row}">
          <el-tag :type="row.completed ? 'success' : 'info'">
            {{ row.completed ? '已完成' : '未完成' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{row, $index}">
          <el-button
            size="small"
            :type="row.completed ? 'info' : 'success'"
            @click="toggleTodo(row)"
          >
            {{ row.completed ? '标记未完成' : '标记完成' }}
          </el-button>
          <el-button size="small" type="danger" @click="removeTodo($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const newTodo = ref('')
const todos = ref([])

// 从本地存储加载数据
onMounted(() => {
  const savedTodos = localStorage.getItem('todos')
  if (savedTodos) {
    todos.value = JSON.parse(savedTodos)
  }
})

const addTodo = () => {
  if (!newTodo.value.trim()) {
    ElMessage.warning('请输入内容')
    return
  }

  todos.value.push({
    id: Date.now(),
    content: newTodo.value,
    completed: false
  })

  saveToLocal()
  newTodo.value = ''
}

const toggleTodo = (todo) => {
  todo.completed = !todo.completed
  saveToLocal()
}

const removeTodo = (index) => {
  todos.value.splice(index, 1)
  saveToLocal()
}

const saveToLocal = () => {
  localStorage.setItem('todos', JSON.stringify(todos.value))
}
</script>

<style scoped>
.todo-container {
  padding: 20px;
}
</style>
